<template>
  <div id="container" ref="mapContainer"></div>
  <div class="input-card">
    <div class="input-item">
      <el-input
        v-model="driver"
        placeholder="请输入司机姓名搜索"
        prefix-icon="Search"
        class="my-input"
        @blur="show"
      />
    </div>
    <div
      class="one"
      v-for="(item, index) in tableDiv"
      :key="item.id"
      @click="handleClick(index, item)"
      :ref="setRef(index)"
    >
      <div class="two">
        <el-row :gutter="2">
          <el-col :span="4">
            <span
              ><el-icon
                style="
                  margin-left: 10px;
                  width: 30px;
                  margin-top: 2px;
                  color: #9a9a9a;
                "
                ><Van /></el-icon
            ></span>
          </el-col>
          <el-col :span="16">
            <span>运单号：{{ item.wb_number }}</span>
          </el-col>
        </el-row>
      </div>
      <div class="three">
        <el-row :gutter="2">
          <el-col :span="14">
            <span>车牌号：{{ item.vc_id }}</span>
          </el-col>
          <el-col :span="6">
            <span>司机：{{ item.dv_id }}</span>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="my_pagination">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :size="size"
        :background="background"
        layout="total, prev, pager, next"
        :total="count"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import {
  onMounted,
  onUnmounted,
  ref,
  reactive,
  compile,
  computed,
  nextTick,
} from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import $http from "@/axios/base.js";
export default {
  name: "app",
  setup() {
    const currentPage = ref(1);
    const pageSize = ref(6);
    const size = ref("small");
    const background = ref(true);
    const count = ref(6);
    const tableDiv = ref();
    const divRefs = ref([]);
    // const tableDiv = ref([
    //   {
    //     id: 1,
    //     ydh: "Y20170725021",
    //     cph: "沪DT8888",
    //     sj: "林江",
    //     address: "长沙市雨花区",
    //   },
    //   {
    //     id: 2,
    //     ydh: "Y20170725022",
    //     cph: "沪DT8888",
    //     sj: "林江",
    //     address: "长沙市雨花区",
    //   },
    //   {
    //     id: 3,
    //     ydh: "Y20170725023",
    //     cph: "沪DT8888",
    //     sj: "林江",
    //     address: "长沙市芙蓉区",
    //   },
    //   {
    //     id: 4,
    //     ydh: "Y20170725023",
    //     cph: "沪DT8888",
    //     sj: "林江",
    //     address: "长沙市岳麓区",
    //   },
    //   {
    //     id: 5,
    //     ydh: "Y20170725023",
    //     cph: "沪DT8888",
    //     sj: "林江",
    //     address: "长沙市天心区",
    //   },
    //   {
    //     id: 6,
    //     ydh: "Y20170725023",
    //     cph: "沪DT8888",
    //     sj: "林江",
    //     address: "长沙市望城区",
    //   },
    // ]);
    // const wb_meter = reactive({
    //   audit_status: 1,
    //   bill_method: 1,
    //   collect: 1,
    //   cr_id: 1,
    //   create_by: "1",
    //   create_time: "2024-02-02T00:00:00",
    //   det_place: "1",
    //   dv_id: 1,
    //   freight_costs: 1,
    //   freight_count: 1,
    //   handling_fee: 1,
    //   last_by: "1",
    //   last_time: "2024-02-02T00:00:00",
    //   ord_id: 1,
    //   order_time: "2024-02-02T00:00:00",
    //   origin_place: "1",
    //   other_fee: 1,
    //   packag_fee: 1,
    //   pay_as_you_go: 1,
    //   pay_count: 1,
    //   payable_status: 1,
    //   periodical_payment: 1,
    //   plan_time: "2024-02-02T00:00:00",
    //   planget_time: "2024-02-02T00:00:00",
    //   prepayment: 1,
    //   reality_time: "2024-02-02T00:00:00",
    //   realityget_time: "2024-02-02T00:00:00",
    //   tran_manager: 1,
    //   vc_id: 1,
    //   wb_id: 5,
    //   wb_number: "1",
    //   wb_status: 1,
    // });
    const wb_meter = ref({});
    const infoWindow = reactive({
      visible: false,
      content: computed(() => {
        return `
        <div style="background-color: #fff; border-radius: 50%; padding: 10px;" class="info-window-content ${
          isActive ? "active" : ""
        }">
          <div style="font-size:18px;">运单号：${wb_meter.value.wb_number}</div>
          <div style="font-size:14px;margin-top:10px;margin-bottom:15px;"><span style="margin-right:10px">车牌号：${
            wb_meter.value.vc_id
          }</span> <span>司机：${
          wb_meter.value.dv_id
        } (15408090099)</span></div>
          <hr style="border-color:#F2F2F2;color:#F2F2F2"/>
          <div style="font-size:14px;margin-left:10px;margin-top:10px;margin-bottom:5px"><span style="color:#9A9A9A">车辆位置：</span>上海市世纪大道1954号</div>
          <div style="font-size:14px;margin-left:10px;margin-top:5px;margin-bottom:5px"><span style="color:#9A9A9A">发车时间：</span>${new Date(wb_meter.value.reality_time)
            .toISOString()
            .slice(0, 10)
            .toString()}</div>
          <div style="font-size:14px;margin-left:10px;margin-top:5px;margin-bottom:10px"><span style="color:#9A9A9A">预计到达时间：</span>${new Date(wb_meter.value.planget_time)
            .toISOString()
            .slice(0, 10)
            .toString()}</div>
          <hr style="border-color:#F2F2F2;color:#F2F2F2"/>
          <p><span style="display: inline-block;background-color:#FF9138;padding:5px 8px;border-radius:5px;color:#eee;">发</span><span style="display: inline-block;background-color:#FFF4EB;padding:5px;width:300px;font-size:14px;"> &nbsp;${
            wb_meter.value.origin_place
          }</span></p>
          <p><span style="display: inline-block;background-color:#2ED477;padding:5px 8px;border-radius:5px;color:#eee;">收</span><span style="display: inline-block;background-color:#EBFBF2;padding:5px;width:300px;font-size:14px;"> &nbsp;${
            wb_meter.value.det_place
          }</span></p>
        </div>
      `;
      }),
    });
    const isActive = ref(false);
    const mapContainer = ref(null);
    const map = ref(null);
    const driver = ref();
    const driving = ref(null); // 驾车导航实例引用
    const startPoint = [116.404, 39.915]; // 起点坐标
    const endPoint = [116.45, 39.9]; // 终点坐标
    const marker = ref(null);
    const polyline = ref(null);
    const passedPolyline = ref(null);
    const geocoder = ref(null);
    const lnglat = ref("");
    const lineArr = ref([
      [112.982488, 28.203045],
      // [112.982489, 28.203089],
      // [112.982658, 28.203084],
      // [112.982711, 28.20334],
      // [112.982641, 28.203426],
      // [112.982652, 28.203516],
      // [112.982689, 28.203582],
      // [112.98269018562212, 28.203338573274518],
      // [112.98267432884597, 28.203543527890517],
      // [112.98263300000008, 28.20343999999999],
      // [112.982818, 28.203808],
      // [112.984294, 28.203599],
      // [112.990608, 28.203427],
      // [112.992362, 28.20354],
      // [113.030701, 28.208845],
      // [113.03091, 28.208566],
      // [113.031028, 28.206871],
      // [113.033807, 28.14296],
      // [113.035642, 28.135664],
      // [113.037734, 28.135734],
      // [113.038471, 28.135788],
      // [113.03853, 28.135795],
      // [116.478935, 39.997761],
      // [116.478939, 39.997825],
      // [116.478912, 39.998549],
      // [116.478912, 39.998549],
      // [116.478998, 39.998555],
      // [116.478998, 39.998555],
      // [116.479282, 39.99856],
      // [116.479658, 39.998528],
      // [116.480151, 39.998453],
      // [116.480784, 39.998302],
      // [116.480784, 39.998302],
      // [116.481149, 39.998184],
      // [116.481573, 39.997997],
      // [116.481863, 39.997846],
      // [116.482072, 39.997718],
      // [116.482362, 39.997718],
      // [116.483633, 39.998935],
      // [116.48367, 39.998968],
      // [116.484648, 39.999861],
    ]);
    var startLngLat = ref(); //起始点坐标
    var endLngLat = ref(); //终点坐标
    const truckDriving = ref(null); // 货车路径规划实例
    const path = ref(null); // 路径规划结果
    const currentIndex = ref(0);

    const setRef = (index) => (el) => {
      // divRefs.value[index] = el; // 将当前循环的索引和对应的 div 元素添加到引用数组中
      divRefs.value[index] = el;
    };

    const handleClick = (index, row) => {
      // console.log(tableDiv.value[index].origin_place);
      lineArr.value = [];
      geoCode(tableDiv.value[index].det_place, "det_place");
      geoCode(tableDiv.value[index].origin_place, "origin_place");
      // 移除之前选中的 div 元素的样式，如果有的话
      if (currentIndex.value !== -1) {
        divRefs.value[currentIndex.value].classList.remove("active");
      }
      divRefs.value[index].classList.add("active");
      // console.log(row);
      currentIndex.value = index;
      getWb(row.wb_id);
    };

    const getWb = (wb_id) => {
      $http
        .get(`http://localhost:5261/api/Tracks/GetWb/${wb_id}`)
        .then((res) => {
          wb_meter.value = res;
          getDriver(res.dv_id);
          getVehicles(res.vc_id);
          if (infoWindowInstance.value != undefined)
            infoWindowInstance.value.close();
        })
        .catch((err) => console.log(err));
    };

    const geoCode = async (address, name) => {
      if (geocoder.value == undefined) {
        geocoder.value = new Promise((resolve) => {
          amap.value.plugin(["AMap.Geocoder"], () => {
            resolve(new amap.value.Geocoder());
          });
        });
      }
      const geocoderInstance = await geocoder.value;
      lineArr.value = [];
      console.log(lineArr.value);
      geocoderInstance.getLocation(address, (status, result) => {
        if (status === "complete" && result.geocodes.length) {
          const lnglatValue = result.geocodes[0].location;
          lnglat.value = lnglatValue;
          console.log(address);
          if (name == "origin_place") {
            marker.value.setPosition(lnglatValue);
            map.value.add(marker.value);
            map.value.setFitView(marker.value);
            startLngLat.value = [lnglat.value.lng, lnglat.value.lat];
            lineArr.value[0] = [lnglat.value.lng, lnglat.value.lat];
          } else if (name == "det_place")
            endLngLat.value = [lnglat.value.lng, lnglat.value.lat];
          if (startLngLat.value != undefined && endLngLat.value != undefined)
            getlnglat();
          // console.log(startLngLat.value);
        } else {
          console.error("根据地址查询位置失败");
        }
      });
    };

    const show = async (value) => {
      await $http
        .get(
          `http://localhost:5261/api/Tracks/GetMeters/${currentPage.value},${pageSize.value}`,
          {
            params: {
              name: driver.value,
            },
          }
        )
        .then((res) => {
          console.log(res);
          tableDiv.value = res;
          if (driver.value != null) {
            handleClick(0, res[0]);
          }
          if (value != undefined) {
            handleClick(0, res[0]);
          }
          tableDiv.value.forEach((item, index) => {
            getDriver(item.dv_id, index);
            getVehicles(item.vc_id, index);
          });
          getCount();
        })
        .catch((err) => console.log(err));
    };

    const getDriver = (id, index) => {
      $http
        .get(`http://localhost:5261/api/Tracks/GetDriver/${id}`)
        .then((res) => {
          if (index != undefined) tableDiv.value[index].dv_id = res.dv_name;
          else wb_meter.value.dv_id = res.dv_name;
        })
        .catch((err) => console.log(err));
    };

    const getVehicles = (id, index) => {
      $http
        .get(`http://localhost:5261/api/Tracks/GetVehicles/${id}`)
        .then((res) => {
          if (index != undefined) tableDiv.value[index].vc_id = res.vc_phone;
          else wb_meter.value.vc_id = res.vc_phone;
        })
        .catch((err) => console.log(err));
    };

    const getCount = () => {
      $http
        .get(`http://localhost:5261/api/Tracks/GetCount`, {
          params: {
            name: driver.value,
          },
        })
        .then((res) => {
          // console.log(res);
          count.value = res;
        })
        .catch((err) => console.log(err));
    };

    const startAnimation = () => {
      marker.value.moveAlong(lineArr.value, {
        duration: 500, // 每一段的时长，可根据实际采集时间间隔设置
        autoRotation: true, // 是否延道路自动设置角度在 moveAlong 里设置
      });
    };

    const handleCurrentChange = (value) => {
      currentPage.value = value;
      show(value);
    };

    const handleSizeChange = (value) => {
      pageSize.value = value;
      show(value);
    };

    const pauseAnimation = () => {
      marker.value.pauseMove();
    };

    const resumeAnimation = () => {
      marker.value.resumeMove();
    };

    const stopAnimation = () => {
      marker.value.stopMove();
    };

    const initAMap = () => {
      map.value = new amap.value.Map(mapContainer.value, {
        resizeEnable: true,
        center: startLngLat.value,
        zoom: 17,
      });
      geocoder.value = new Promise((resolve) => {
        amap.value.plugin(["AMap.Geocoder"], () => {
          resolve(
            // new AMap.Geocoder({
            //   city: "010", //城市设为北京，默认：“全国”
            // })
            new amap.value.Geocoder()
          );
        });
      });
      marker.value = new AMap.Marker({
        map: map.value,
        position: lineArr.value[0],
        icon: new amap.value.Icon({
          // 使用 AMap.Icon 来设置自定义的标记图标
          size: new amap.value.Size(19, 31), // 设置图标的大小，单位为像素
          imageSize: new amap.value.Size(19, 31), // 设置图标图片的大小，单位为像素，如果与 size 不一致，图标将被缩放显示
          image: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png", // 设置图标的图片路径，可以使用绝对路径或者相对路径，但需要确保图片能够被正确加载
          imageOffset: new amap.value.Pixel(0, 0), // 设置图标在图片中的偏移量，单位为像素，默认为 (0, 0)，表示从图片左上角开始显示图标。如果需要调整图标在图片中的位置，可以修改这个参数的值。
        }),
        offset: new amap.value.Pixel(-13, -26),
      });
      marker.value.on("click", handleMarkerClick);

      amap.value.plugin("AMap.Driving", function () {
        driving.value = new amap.value.Driving({
          policy: 0, //驾车路线规划策略，0是速度优先的策略
        });
      });

      map.value.setFitView(); // 将地图视野调整到适合所有覆盖物的视野范围
    };

    const getlnglat = () => {
      console.log(startLngLat.value);
      console.log(endLngLat.value);
      driving.value.search(
        startLngLat.value,
        endLngLat.value,
        function (status, result) {
          //status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
          //查询成功时，result 即为对应的驾车导航信息
          console.log("路径状态：" + status);
          console.log(result);
          result.routes[0].steps.forEach((item, index) => {
            lineArr.value[index] = [
              item.start_location.lng,
              item.start_location.lat,
            ];
          });
          console.log(lineArr.value);
          drawRoute();
        }
      );
    };

    // 绘制路线点的方法
    const drawRoute = () => {
      // 清除之前的路线图层（如果有的话）
      map.value.clearMap();
      // 创建一个折线对象，并设置路线点和样式
      const line = new amap.value.Polyline({
        path: lineArr.value,
        strokeColor: "#FF33FF", // 路线颜色
        strokeWeight: 6, // 路线粗细
        strokeOpacity: 0.8, // 路线透明度
      });
      marker.value = new amap.value.Marker({
        map: map.value,
        position: lineArr.value[0],
        icon: new amap.value.Icon({
          // 使用 AMap.Icon 来设置自定义的标记图标
          size: new amap.value.Size(19, 31), // 设置图标的大小，单位为像素
          imageSize: new amap.value.Size(19, 31), // 设置图标图片的大小，单位为像素，如果与 size 不一致，图标将被缩放显示
          image: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png", // 设置图标的图片路径，可以使用绝对路径或者相对路径，但需要确保图片能够被正确加载
          imageOffset: new amap.value.Pixel(0, 0), // 设置图标在图片中的偏移量，单位为像素，默认为 (0, 0)，表示从图片左上角开始显示图标。如果需要调整图标在图片中的位置，可以修改这个参数的值。
        }),
        offset: new amap.value.Pixel(-13, -26),
      });
      marker.value.on("click", handleMarkerClick);
      // 将折线添加到地图上
      line.setMap(map.value);
    };

    const amap = ref();

    const handleMarkerClick = () => {
      // 处理小车标记的点击事件，显示隐藏的框
      // infoWindow.visible = true;
      // 将隐藏的框定位到小车标记的位置
      const position = marker.value.getPosition();
      infoWindowInstance.value = new amap.value.InfoWindow({
        content: infoWindow.content, // 设置隐藏的框的内容为infoWindow.content
        offset: new amap.value.Pixel(0, -10), // 调整隐藏的框的位置，使其显示在小车下方
      });
      infoWindowInstance.value.open(map.value, position); // 打开隐藏的框并定位到小车标记的位置
    };

    const infoWindowInstance = ref();

    onMounted(async () => {
      await show();
      window._AMapSecurityConfig = {
        securityJsCode: "1c556528b78305b472619a14534e47a6",
      };
      AMapLoader.load({
        key: "1a1bf22816ee91a0ac4f00ffb1811f7c", // 替换为你自己的高德地图AK密钥
        version: "2.0", // 指定要加载的 JSAPI 的版本
        plugins: ["AMap.MoveAnimation", "AMap.TrafficLayer"], // 需要使用的插件列表，如驾车导航'AMap.Driving'等
        AMapUI: {
          // 如果需要使用 AMapUI，可以在这里配置相关参数，如版本号等。如果不使用，可以忽略这部分配置。
          version: "1.1", // 指定要加载的 AMapUI 的版本号，默认为最新版本。
          // 其他配置项，如资源文件的路径等，可以根据需要进行配置。具体可参考官方文档。
        },
        Loca: {
          // 如果需要使用 Loca，可以在这里配置相关参数，如版本号等。如果不使用，可以忽略这部分配置。
          version: "2.0", // 指定要加载的 Loca 的版本号，默认为最新版本。
          // 其他配置项，如资源文件的路径等，可以根据需要进行配置。具体可参考官方文档。
        },
      })
        .then((AMap) => {
          amap.value = AMap;
          geoCode(tableDiv.value[0].det_place, "det_place");
          geoCode(tableDiv.value[0].origin_place, "origin_place");
          loadData();
          initAMap(); // 调用初始化地图方法，并将 AMap 对象作为参数传递进去
        })
        .catch((e) => {
          console.log(e); // 处理加载错误
        });
    });

    const loadData = () => {
      // 模拟数据加载的过程，可以使用 axios 等库来发起网络请求获取数据
      setTimeout(() => {
        const firstDiv = divRefs.value[0]; // 获取第一个循环生成的 div 元素的引用
        firstDiv.classList.add("active");
        getWb(tableDiv.value[0].wb_id);
      }, 500); // 模拟数据加载需要的时间，可以根据实际情况进行调整
    };

    onUnmounted(() => {
      map.value?.destroy();
    });

    return {
      setRef,
      wb_meter,
      handleClick,
      mapContainer,
      show,
      startAnimation,
      initAMap,
      pauseAnimation,
      resumeAnimation,
      stopAnimation,
      handleCurrentChange,
      handleSizeChange,
      currentPage,
      pageSize,
      size,
      background,
      count,
      tableDiv,
      driving,
      endPoint,
      startPoint,
      map,
      driver,
      marker,
      polyline,
      passedPolyline,
      lineArr,
      geocoder,
    };
  },
};
</script>

<style scoped>
.one.active {
  border-color: blue;
  background-color: #e6f1ff;
  color: blue;
}

.info-window-content {
  background-color: #fff;
  border-radius: 10px;
  padding: 10px;
}
.info-window-content p {
  margin: 0;
}
.info-window-content p:not(:last-child) {
  margin-bottom: 5px;
}
.info-window-content .address {
  background-color: #f9f9f9;
  padding: 5px 10px;
  border-radius: 5px;
  display: inline-block;
  margin-right: 10px;
}

.box_div {
  width: 200px;
  height: 100px;
  background-color: #000;
  border-radius: 80px; /* 指定四个角的圆角半径为 10px */
}

.my-input {
  width: 310px;
  height: 40px;
}

.my_pagination {
  width: 313px;
  display: flex;
  justify-content: right;
  line-height: 50px;
}

.one {
  border: 1px solid #d1d1d1;
  margin-top: 10px;
}

.two {
  z-index: 1;
  font-size: 17px;
  padding-top: 20px;
  /* padding-bottom: 10px; */
}
.three {
  font-size: 14px;
  color: #9a9a9a;
  padding-top: 16px;
  padding-bottom: 20px;
}

html,
body,
#container {
  height: 100%;
  width: 100%;
}

html {
  font-size: 12px;
}

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji",
    "Segoe UI Symbol", "Noto Color Emoji";
  line-height: 1.5;
  font-weight: 300;
  color: #111213;
}

.input-card {
  height: 810px;
  display: flex;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  border-radius: 0.25rem;
  width: 22rem;
  border-width: 0;
  border-radius: 0.4rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
  position: fixed;
  bottom: 3rem;
  right: 3rem;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  padding: 0.75rem 1.25rem;
}
</style>